package com.lysj.bhp.scheduled.job;


import com.lysj.bhp.scheduled.base.ScheduledContent;
import com.lysj.bhp.scheduled.domain.DiamondBitcoinWallet;
import com.lysj.bhp.scheduled.domain.RechargeRecord;
import com.lysj.bhp.util.http.HttpUtil;
import com.lysj.bhp.util.web.ParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

@Component
public class DiamondBitcoinJob extends ScheduledContent {

    private static Logger logger = LoggerFactory.getLogger(DiamondBitcoinJob.class);

    private static String DIAMOND_BTC_BALANCE_URL = "http://20.184.13.116/v2/addr/";

    /*第一次10秒后执行，当执行完后0.2秒再执行，保证一秒并发不超过5个*/
    @Scheduled(initialDelay = 10000, fixedDelay = 60000)
    public void queryDiamondBitcoinWallet() {
        logger.info("DiamondBitcoinJob is Starting ...");
        DiamondBitcoinWallet diamondBitcoinWallet = diamondBitcoinWalletRepository.findFirstByOrderByLastQueryTimeAsc();
        if (diamondBitcoinWallet == null) {
            return;
        }
        String result = HttpUtil.sendNoParamGet(DIAMOND_BTC_BALANCE_URL + diamondBitcoinWallet.getAddress() + "/balance");//查询bhpc钱包的可用余额
        if (ParamUtil.isBlack(result)) {
            logger.error("网络错误:");
            diamondBitcoinWallet.setLastQueryTime(System.currentTimeMillis());
            diamondBitcoinWalletRepository.save(diamondBitcoinWallet);
            return;
        }
        logger.info("查询余额:" + result + "用户id" + diamondBitcoinWallet.getUserId());
        BigDecimal realBalance = new BigDecimal(result);
        if (realBalance.compareTo(new BigDecimal(BigInteger.ZERO)) < 0) { // !!!即使发生错误,也应该继续执行下一次的查询!!!
            logger.error("DiamondBitcoinJob return -1,diamondBitcoinId is " + diamondBitcoinWallet.getDiamondBitcoinWalletId());
            diamondBitcoinWallet.setLastQueryTime(System.currentTimeMillis());
            diamondBitcoinWalletRepository.save(diamondBitcoinWallet);
            return;
        }
        //返回真实余额,除以10^7;
        realBalance = realBalance.divide(new BigDecimal("10000000"), 8, BigDecimal.ROUND_DOWN);
        if (realBalance.compareTo(diamondBitcoinWallet.getBookKeepBalance()) >= 1) { //查询到的余额大于钱包得真实余额(记账余额)，则更新
            logger.info("DiamondBitcoin Balance Increment,Start Record!" + diamondBitcoinWallet.getDiamondBitcoinWalletId());
            BigDecimal increase = realBalance.subtract(diamondBitcoinWallet.getBookKeepBalance()); // 增加的余额
            diamondBitcoinWallet.setBalance(diamondBitcoinWallet.getBalance().add(increase));//更新钱包的总额
            diamondBitcoinWallet.setAvailBalance(diamondBitcoinWallet.getAvailBalance().add(increase));//更新钱包的可用余额
            // 创建充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCoinType(30);
            rechargeRecord.setPayAmount(increase);
            rechargeRecord.setUserId(diamondBitcoinWallet.getUserId());
            rechargeRecord.setCreateTime(new Date());
            rechargeRecord.setAuthentication("成功");
            rechargeRecord.setName("BCD");
            rechargeRecord.setChineseName("比特钻石");
            rechargeRecord.setAddress("0x" + diamondBitcoinWallet.getAddress());
            rechargeRecordRepository.save(rechargeRecord);
        }
        diamondBitcoinWallet.setBookKeepBalance(realBalance);//更新钱包的记账余额
        diamondBitcoinWallet.setLastQueryTime(System.currentTimeMillis()); // 将最近的查询时间设置为现在
        diamondBitcoinWalletRepository.save(diamondBitcoinWallet);
    }

}
